package com.yotta.operationdatascreencode.common.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.id.NanoId;
import cn.hutool.core.util.StrUtil;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import com.yotta.operationdatascreencode.common.config.CosConfig;
import com.yotta.operationdatascreencode.common.exception.BusinessException;
import java.io.File;
import java.io.IOException;
import java.util.Objects;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

/**
 * 文件工具类
 */
@Slf4j
@Component
@Lazy
public class FileUtils {
    private static  String secretId = CosConfig.getSecretId();
    private static  String secretKey = CosConfig.getSecretKey();
    private static  String bucketName = CosConfig.getBucketName();
    private static  String region = CosConfig.getRegion();

    //
    private static BasicCOSCredentials cred = new BasicCOSCredentials(secretId, secretKey);


    private static ClientConfig clientConfig = new ClientConfig(new Region(region));


    private static COSClient cosClient = new COSClient(cred, clientConfig);

    private static String toCos(MultipartFile file,String path) throws IOException {
        String dateString = DateUtil.today().replace("-", "");
        String prefix = NanoId.randomNanoId(8);
        String originalFilename = file.getOriginalFilename();
        String keyPath = null;
        if (StrUtil.isBlank(path)) {
            keyPath = "zhiyejiaoyu/common";
        } else {
            keyPath = "zhiyejiaoyu/" + path;
        }
        String key = keyPath + "/" + StrUtil.format("{}_{}_{}", prefix,
            dateString, originalFilename);
        File tempFile = FileUtil.createTempFile();
        try {
            file.transferTo(tempFile);
            PutObjectRequest putObjectRequest = new PutObjectRequest(CosConfig.getBucketName(),
                key, tempFile);
            PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
            String eTag = putObjectResult.getETag();
        } finally {
            if (FileUtil.exist(tempFile)) {
                FileUtil.del(tempFile);
            }
        }
        return key;
    }


    private static final String fileCheck2Extension(MultipartFile file) {
        int fileNamelength = Objects.requireNonNull(file.getOriginalFilename()).length();
        if (fileNamelength > Integer.parseInt(CosConfig.getNameLenth())) {
            throw new BusinessException("文件名称超长限制异常");
        }
        assertAllowed(file, CosConfig.getAllowExtensions());
        return getExtension(file);
    }


    private static final void assertAllowed(MultipartFile file, String[] allowedExtension) {
        long size = file.getSize();
        if (size > Long.parseLong(CosConfig.getMaxSize())) {
            long defaultSize = Long.parseLong(CosConfig.getMaxSize()) / 1024 / 1024;
            throw new BusinessException(defaultSize <= 0
                ? String.valueOf(1L) : String.valueOf(defaultSize));
        }
        String fileName = file.getOriginalFilename();
        String extension = getExtension(file);
        if (allowedExtension != null && !isAllowedExtension(extension, allowedExtension)) {
            if (allowedExtension == MimeTypeUtils.IMAGE_EXTENSION) {
                throw new BusinessException(fileName);
            } else if (allowedExtension == MimeTypeUtils.FLASH_EXTENSION) {
                throw new BusinessException(fileName);
            } else if (allowedExtension == MimeTypeUtils.MEDIA_EXTENSION) {
                throw new BusinessException(fileName);
            } else if (allowedExtension == MimeTypeUtils.VIDEO_EXTENSION) {
                throw new BusinessException(fileName);
            } else {
                throw new BusinessException(fileName);
            }
        }

    }

    private static final boolean isAllowedExtension(String extension, String[] allowedExtension) {
        for (String str : allowedExtension) {
            if (str.equalsIgnoreCase(extension)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 获取文件名的后缀
     * @param file 表单文件
     * @return 后缀名
     */
    private static final String getExtension(MultipartFile file) {
        String extension = FilenameUtils.getExtension(file.getOriginalFilename());
        if (StrUtil.isEmpty(extension)) {
            extension = MimeTypeUtils.getExtension(Objects.requireNonNull(file.getContentType()));
        }
        return extension;
    }

    /**
     * 上传
     * @param file file
     * @return String
     * @throws IOException 异常
     */
    public static String upload(MultipartFile file,String path) throws IOException {
        //不检查文件后缀
        //fileCheck2Extension(file);
        return fileFullPath(toCos(file,path));
    }

    /**
     * 可访问的文件全路径
     * @param key key
     * @return String
     */
    private static String fileFullPath(String key) {
        return StrUtil.format("{}/{}", CosConfig.getPathPrefix(), key);
    }
}
